import { Navigate, useLocation } from 'react-router-dom';
import { ROLE_ROUTES } from '../../constants/permissions';

const AuthRoute = ({ children }) => {
  const location = useLocation();
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  const userRole = userInfo.role || 'user';

  if (!isLoggedIn) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 检查用户是否有权限访问当前路由
  const allowedRoutes = ROLE_ROUTES[userRole] || [];
  const currentPath = location.pathname;
  
  if (!allowedRoutes.some(route => currentPath.startsWith(route))) {
    // 如果用户没有权限访问当前路由，重定向到第一个有权限的路由
    return <Navigate to={allowedRoutes[0] || '/login'} replace />;
  }

  return children;
};

export default AuthRoute;